/**
 * 作者: 会写BUG
 * 创作日期: 2025/3/26 22:31
 * 描述: cwbQtPractice.ScorePanel
 *
 *
 **/

#pragma once

#include "score_panel.h"
#include "game_button.h"
#include "score_record.h"

#include <QPainter>
#include <QGridLayout>
#include <QLabel>

ScorePanel::ScorePanel(QWidget *_parent)
    : QWidget(_parent) {

    initUI();
    initConnect();
}

ScorePanel::~ScorePanel() {

}

void ScorePanel::updateScore()
{
    score_label_->setText(QString::number(ScoreRecord::instance()->score()));
    top_score_label_->setText(QString("Top: %1").arg(ScoreRecord::instance()->topScore()));
}

void ScorePanel::initUI()
{
    auto score_layout = new QGridLayout(this);
    score_layout->setVerticalSpacing(8);
    score_layout->setHorizontalSpacing(8);
    score_layout->setContentsMargins(8, 8, 8, 8);
    score_layout->setColumnStretch(0, 1);
    score_layout->setColumnStretch(1, 1);
    score_layout->setRowStretch(0, 1);
    score_layout->setRowStretch(1, 1);

    score_label_ = new QLabel("0", this);
    score_label_->setFont(QFont("Arial", 30, QFont::Bold));
    score_label_->setAlignment(Qt::AlignCenter);
    top_score_label_ = new QLabel("Top: 0", this);
    top_score_label_->setFont(QFont("Arial", 20, QFont::Bold));
    top_score_label_->setAlignment(Qt::AlignCenter);

    score_layout->addWidget(score_label_, 0, 0, 2, 1);
    score_layout->addWidget(top_score_label_, 0, 1, 1, 1);

    undo_btn_ = new GameButton("撤销");
    undo_btn_->setFont(QFont("Arial", 16, QFont::DemiBold));
    undo_btn_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    menu_btn_ = new GameButton("菜单");
    menu_btn_->setFont(QFont("Arial", 16, QFont::DemiBold));
    menu_btn_->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    auto btn_layout = new QHBoxLayout();
    btn_layout->setSpacing(8);
    btn_layout->setContentsMargins(0, 0, 0, 0);
    btn_layout->addWidget(undo_btn_);
    btn_layout->addWidget(menu_btn_);

    score_layout->addLayout(btn_layout, 1, 1, 1, 1);
}

void ScorePanel::initConnect()
{
    connect(menu_btn_, &GameButton::clicked, this, &ScorePanel::menuClicked);

    connect(SCORE_RECORD, &ScoreRecord::chessChanged,
                this, &ScorePanel::updateScore);
}

void ScorePanel::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);

    painter.setPen(Qt::transparent);
    painter.setBrush(QColor(227, 174, 106));
    painter.drawRect(0, 0, width(), height());

    QMargins margins = layout()->contentsMargins();

    painter.drawRect(margins.left(), margins.top(),
                     width() - margins.left() - margins.right(),
                     height() - margins.top() - margins.bottom());

    painter.setBrush(QColor(229, 192, 148));
    painter.drawRect(score_label_->geometry());
    painter.drawRect(top_score_label_->geometry());

}
